package com.szosen.bluetooth;

import java.io.IOException;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

public class mBluetoothService {

	private Handler mHandler = null;
	private int mState = STATE_NONE;
	private BluetoothAdapter btAdapter;
	public static final int STATE_NONE = 0x401180; // 空闲状态
	public static final int STATE_CONNECTING = 0x401181; // 正在连接
	public static final int STATE_CONNECTED = 0x401182; // 已经建立蓝牙连

	public static final int MESSAGE_DEVICE = 0x401183;// 传递蓝牙设备名称和地址
	public static final int MESSAGE_STATE_CHANGE = 0x401184;// 适配器状态改变信号
	public static final int MESSAGE_READ = 0x401185;// 读入数据信号
	public static final int MESSAGE_WRITE = 0x401186;// 写入数据信号
	public static final int MESSAGE_TOAST = 0x401187;// 显示给用户的提示的信号
	public static final String TOAST = "toast";
	private Handler handler;
	private static final String UUIDS = "00001101-0000-1000-8000-00805F9B34FB";
	private static final UUID MY_UUID = UUID.fromString(UUIDS);// 建立蓝牙连接的UUID

	/*public enum BluetoothConnectionState {
		DISCONNECTED, CONNECTED, CONNECTING, IOEXCEPTION, INTERRUPTEDEXCEPTION;
	}*/

	public mBluetoothService(Handler handler) {
		this.handler = handler;
		btAdapter = BluetoothAdapter.getDefaultAdapter();
	}

	/*
	 * private void search(){ if(!btAdapter.isEnabled()){ btAdapter.enable(); }
	 * /
	 * /因为是服务类而不是activity，而不能启动另外的activity。....................................
	 * ... .......... Intent enable = new
	 * Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
	 * enable.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 3600);
	 * //3600为蓝牙设备可见时间 startActivity(enable);
	 * 
	 * }
	 */
	/**
	 * 通过设备名称或者地址来查询设备
	 * 
	 * @param str
	 *            地址或者设备名
	 * @return 设备
	 */
	public BluetoothDevice searchBondedDevice(String str) {
		Set<BluetoothDevice> bluetoothDevices = btAdapter.getBondedDevices();
		for (BluetoothDevice bluetoothDevice : bluetoothDevices) {
			if (bluetoothDevice.getName().equalsIgnoreCase(str)
					|| bluetoothDevice.getAddress().equalsIgnoreCase(str)) {
				return bluetoothDevice;
			}
		}
		return null;
	}

	public BluetoothDevice getRemoteDeviceByAddress(String address) {
		return btAdapter.getRemoteDevice(address);
	}
	
	private void setState(int state) {
		
		this.mState = state;
		// 将状态改变信息传递给UI界面
		handler.obtainMessage(MESSAGE_STATE_CHANGE, state, -1).sendToTarget();
	}
	
	/**
	 * 处理连接建立失败，通知界面
	 */
	private void connectionFailed() {
		Message msg = handler.obtainMessage(MESSAGE_TOAST);
		Bundle bundle = new Bundle();
		bundle.putString(TOAST, "设备连接失败");
		msg.setData(bundle);
		handler.sendMessage(msg);
		setState(STATE_NONE);// 设置状态为空闲
	}
	
	public void connectionLost() {
		Message msg = handler.obtainMessage(MESSAGE_TOAST);
		Bundle bundle = new Bundle();
		bundle.putString(TOAST, "设备连接断开");
		msg.setData(bundle);
		handler.sendMessage(msg);
		if (connectedThread != null) {
			connectedThread.cancel();
			connectedThread = null;
		}
		setState(STATE_NONE);
	}
	
	private mConnectThread connectThread=null;
	private mConnectedThread connectedThread=null;
	
	public void toConnect(BluetoothDevice device){
		if (connectThread != null) {
			connectThread.cancel();
			connectThread = null;
		}
		
		// 断开已经建立好连接
		if (connectedThread != null) {
			// 先关闭流
			connectedThread.cancel();
			connectedThread = null;
		}
		try {
			connectThread=new mConnectThread(device);
			connectThread.start();
			setState(STATE_CONNECTING);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	private class mConnectThread extends Thread {
		private final BluetoothSocket mSocket;
		private final BluetoothDevice mDevice;

		public mConnectThread(BluetoothDevice device) {
			mDevice = device;
			BluetoothSocket tempSocket = null;
			try {
				tempSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
			} catch (Exception e) {
			}
			mSocket = tempSocket;
		}

		@Override
		public void run() {
			btAdapter.cancelDiscovery();
			try {
				mSocket.connect();
			} catch (Exception e) {
				// TODO: handle exception
				try {
					mSocket.close();
				} catch (Exception e2) {
					// TODO: handle exception
				}
				
				return;
			}
			if (mSocket!=null) {
				manageConnectedSocket(mSocket);
			}
			
		}

		public void cancel() {
			try {
				mSocket.close();
			} catch (IOException e) {

			}
		}
	}

	private class mConnectedThread extends Thread {
		private final BluetoothSocket socket;
		private final InputStream inputStream;
		private final OutputStream outputStream;

		public mConnectedThread(BluetoothSocket mSocket) {
			socket = mSocket;
			InputStream tempIn = null;
			OutputStream tempOut = null;
			try {
				tempIn = socket.getInputStream();
				tempOut = socket.getOutputStream();
			} catch (Exception e) {
				// TODO: handle exception

			}
			inputStream = tempIn;
			outputStream = tempOut;
		}

		public void run() {
			byte[] buffer = new byte[1024];
			int bytes;
			while (true) {
				try {
					bytes = inputStream.read(buffer);
					handler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
							.sendToTarget();// 传递给界面更新数据
				} catch (Exception e) {
					// TODO: handle exception
					break;
				}
			}
		}

		public void write(byte[] buffer) {
			try {
				outputStream.write(buffer);
				handler.obtainMessage(MESSAGE_WRITE, -1, 1, buffer)
						.sendToTarget();
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		public void cancel() {
			try {
				socket.close();
				inputStream.close();
				outputStream.close();
			} catch (IOException e) {

			}
		}
	}

	private void manageConnectedSocket(BluetoothSocket mSocket) {
		// TODO Auto-generated method stub
		connectedThread=new mConnectedThread(mSocket);
		connectedThread.start();
		
	}
}
